package zhanglinwei.cryptotools.core.resolver.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import zhanglinwei.cryptotools.core.constant.CryptoToolsConstant;
import zhanglinwei.cryptotools.core.crypto.SM4;
import zhanglinwei.cryptotools.core.resolver.CryptoablePropertyResolver;

import static zhanglinwei.cryptotools.core.crypto.SM4.SM4_PREFIX;
import static zhanglinwei.cryptotools.core.crypto.SM4.SM4_SUFFIX;

public class SM4CBCResolver implements CryptoablePropertyResolver {
    private static final Logger log = LoggerFactory.getLogger(SM4CBCResolver.class);

    @Override
    public boolean isEncrypted(String propertyValue) {
        return propertyValue != null && propertyValue.trim().length() > 0 && propertyValue.startsWith(SM4_PREFIX) && propertyValue.endsWith(SM4_SUFFIX);
    }

    @Override
    public String decrypt(String propertyValue) {
        try {
            String cipherText = propertyValue.substring(SM4_PREFIX.length(), propertyValue.length() - 1);
            return SM4.decrypt_cbc(cipherText);
        } catch (Exception ex) {
            log.error("解密配置值【{}】失败，直接返回原始值", propertyValue);
            return propertyValue;
        }
    }

    @Override
    public String algorithm() {
        return CryptoToolsConstant.SM4_CBC;
    }


}

